package git.soulbgm.security.filter;

import git.soulbgm.common.constant.HttpStatus;
import git.soulbgm.security.constant.SecurityConstants;
import git.soulbgm.security.pojo.LoginUser;
import git.soulbgm.utils.ResponseUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 前登录过滤器
 * 预登录过滤器
 *
 * @author SoulBGM
 * @date 2020-09-08
 */
@Component
public class PreLoginFilter extends OncePerRequestFilter {

    private RequestMatcher matcher;

    public PreLoginFilter() {
        matcher = new AntPathRequestMatcher(SecurityConstants.LOGIN_PROCESSING_URL, "POST");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        boolean flag = false;
        if (matcher.matches(request)) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            // 判断登录的用户是否已登录
            if (authentication != null && authentication.getPrincipal() instanceof LoginUser) {
                flag = true;
            }
        }
        if (flag) {
            ResponseUtil.renderError(response, HttpStatus.FORBIDDEN, "已登录，如需重新登录请退出");
        } else {
            chain.doFilter(request, response);
        }
    }
}
